package pmr.core.finder;

import java.util.Set;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;

import pmr.utils.SCUtils;

public class UnusedMethodsFinder {

	private IJavaSearchScope scope;

	public UnusedMethodsFinder(final IJavaProject javaProject) {
		IPackageFragmentRoot[] packageRoots;
		try {
			packageRoots = javaProject.getPackageFragmentRoots();
			scope = SCUtils.buildScope(packageRoots);
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
	}

	public Set<IMethod> findUnusedMethods(ICompilationUnit unit)
			throws JavaModelException {
		IMethod[] methods = unit.getTypes()[0].getMethods();
		UnusedMethodsRepository repository = new UnusedMethodsRepository(
				methods);

		for (IMethod m : methods) {
			performJavaSearch(m, repository);
		}
		return repository.getUnusedMethods();
	}

	private void performJavaSearch(final IMethod method,
			UnusedMethodsRepository repository) {
		SearchPattern pattern = SearchPattern.createPattern(method,
				IJavaSearchConstants.REFERENCES);
		PMRSimpleSearchRequestor requestor = new PMRSimpleSearchRequestor(
				repository, method);
		SearchEngine searchEngine = new SearchEngine();
		try {
			searchEngine.search(pattern, new SearchParticipant[] { SearchEngine
					.getDefaultSearchParticipant() }, scope, requestor, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

}